# -*- coding: utf-8 -*-
"""
Created on 2022/9/29

@author: Song
"""
from DBTestAnalysisLib import *
import plotnine as G
import streamlit as st

def testStatus4RW(test):
    testCache = {}
    metaList = []
    maxCon = 1
    #
    knownCnt = 0  # 已知项个数
    missingCnt = 0  # 缺失项个数：缺失项总时间估计=missingCnt*已知总时间/已知cnt
    completeTime = 0  # 无需rebuild项的总时间
    rebuildTime = 0  # 需要rebuild项的总时间
    # 先收集好meta信息，然后补充详细信息。
    for dataset in ['energy', 'traffic', 'syn']:
        for tpSize in ['.1', '.all']:  # '.01', '.5', '.9',
            for db in ['TGK', 'TGKI', 'TGL', 'TGLI', 'TGS', 'TGC', 'N1', 'N2', 'PG', 'MA']:  #
                try:
                    testInfo = findValidTest(dataset, db, test, tpSize, maxCon)
                    ti = testInfo[0]
                    raw = fetchLog(ti.tn)
                    if len(raw) == 0:
                        # print('no data: ' + test)
                        missingCnt += 1
                    else:
                        knownCnt += 1
                        completeTime += int(testInfo[2])
                        testCache[ti.tn] = raw
                        metaList.append({
                            'test': ti.test,
                            'system': ti.db,
                            'tp_size': ti.mtpsize,
                            'dataset': ti.dataset,
                            'req_cnt': ti.reqcnt,
                            'test_t': ti.time,
                            'device': testInfo[1],
                            'duration': testInfo[2],
                            'cell_content': ti.time.split(' ')[0] + '(' + ti.reqcnt + ') ' + dur2str(testInfo[2])
                        })
                except DataNotReadyErr as e:
                    missingCnt += 1
    if len(metaList) == 0:
        test.upper() + '[RW]: NO test results on device(data) !'
    else:
        meta = pd.DataFrame(metaList)
        # print(meta)
        toPrint1 = meta.pivot(index=['dataset', 'tp_size'], columns='system', values='cell_content')
        test.upper() + '[RW]: Available test results on device(data)'
        st.dataframe(toPrint1.style.highlight_null(), use_container_width=True)  # apply(highlight_invalid).
        cols = st.columns(4)
        cols[0].metric(label="已完成（浅绿）", value=timeHumanRead(completeTime))  # , delta="{}项".format(knownCnt)
        missingTime = missingCnt * (completeTime + rebuildTime) / knownCnt
        cols[1].metric(label="重构项（灰色）需时", value=timeHumanRead(rebuildTime))
        cols[2].metric(label="缺失项（红色）需时（估计）", value=timeHumanRead(missingTime), delta="{}项".format(missingCnt))
        cols[3].metric(label="全部工作量（估计）", value=timeHumanRead(completeTime + rebuildTime + missingTime), delta="共{}项".format(knownCnt+missingCnt))
        # timeResult(test)


my_progress = st.progress(0)
tabs = st.tabs(["ehistory", "snapshot", "aggmax", "etpc", "reachable", "append", "update"])

with tabs[0]:
    testStatus4RW('ehistory')
    my_progress.progress(15)
with tabs[1]:
    testStatus4RW('snapshot')
    my_progress.progress(30)
with tabs[2]:
    testStatus4RW('aggmax')
    my_progress.progress(45)
with tabs[3]:
    testStatus4RW('etpc')
    my_progress.progress(60)
with tabs[4]:
    testStatus4RW('reachable')
    my_progress.progress(75)
with tabs[5]:
    testStatus4RW('append')
    my_progress.progress(88)
with tabs[6]:
    testStatus4RW('update')
    my_progress.progress(100)